package com.vito.oa.email.util;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.search.AddressStringTerm;

public class OaFromStringTerm extends AddressStringTerm {

	private static final long serialVersionUID = -4622938692744430523L;

	protected OaFromStringTerm(String pattern) {
		super(pattern);
	}

	@Override
	public boolean match(Message msg) {
		Address[] from;

		try {
		    from = msg.getFrom();
		} catch (Exception e) {
		    return false;
		}

		if (from == null)
		    return false;
		for (int i=0; i < from.length; i++)
		    if (fromMatch(from[i]))
			return true;
		return false;
	}
	
	private boolean fromMatch(Address a) {
		if (a instanceof InternetAddress) {
			InternetAddress ia = (InternetAddress) a;
			if (ia.getPersonal() != null) {
				return emailMatch(ia.getPersonal(), pattern, true);
			}
			return false;
		} else
			return emailMatch(a.toString(), pattern, true);
	}
	
	private boolean emailMatch(String s, String pattern, boolean ignoreCase) {
		int len = s.length() - pattern.length();
		for (int i=0; i <= len; i++) {
		    if (s.regionMatches(ignoreCase, i, 
					pattern, 0, pattern.length()))
			return true;
		}
		return false;
	}
	

}
